package initialize

import (
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"os"
	"os/signal"
	"syscall"
)

func InitConsul() {

	config := api.DefaultConfig()

	config.Address = "113.44.72.167:8500"

	// Get a new client
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}
	serviceId := uuid.NewString()
	servicePort := 5003
	serviceName := "order_srv"

	registration := api.AgentServiceRegistration{
		ID:      serviceId,                            //服务唯一ID
		Name:    serviceName,                          //服务名称
		Port:    servicePort,                          //端口号
		Tags:    []string{"commerce", "order", "srv"}, //服务的标签
		Address: "127.0.0.1",                          //服务的Ip地址
	}

	err = client.Agent().ServiceRegister(&registration)
	if err != nil {
		panic(err)
		return
	}

	//捕获系统退出信号，确保服务注销
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		sig := <-c
		fmt.Printf("接收到退出信号：%s,注销服务\n", sig)
		err := client.Agent().ServiceDeregister(serviceId)

		if err != nil {
			panic(errors.New(fmt.Sprintf("无法注销user服务：%v", err)))

		}
		os.Exit(0)
	}()
}
